package cn.com.dingtek.genius.manager.server.service;

import cn.com.dingtek.genius.manager.server.repository.db.entity.CompanyBase;
import cn.com.dingtek.genius.manager.server.repository.db.entity.CompanyDeviceWeb;
import cn.com.dingtek.genius.manager.server.repository.db.entity.DeviceBase;
import cn.com.dingtek.genius.manager.server.repository.db.manager.CompanyBaseManager;
import cn.com.dingtek.genius.manager.server.repository.db.manager.CompanyDeviceWebManager;
import cn.com.dingtek.genius.manager.server.repository.db.manager.DeviceBaseManager;
import cn.com.dingtek.genius.manager.server.support.DeviceSocket;
import cn.com.dingtek.genius.manager.server.support.DeviceType;
import cn.com.dingtek.genius.manager.server.support.PlatformType;
import cn.com.dingtek.genius.manager.server.support.ToWebType;
import cn.com.dingtek.genius.manager.server.utils.MybatisPlusUtil;
import cn.com.dingtek.genius.manager.server.utils.VerifyException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CompanyToWebService {
    @Autowired
    private DeviceBaseManager deviceBaseManager;
    @Autowired
    private CompanyBaseManager companyBaseManager;
    @Autowired
    private CompanyDeviceWebManager companyDeviceWebManager;

    public JSONObject list(DeviceBase param, Long companyId, int currentPage, int pageSize) {
        QueryWrapper<DeviceBase> query = Wrappers.<DeviceBase>query().eq("company_id", companyId);
        if (param != null) {
            query = MybatisPlusUtil.customEqQuery(query, "device_type", param.getDeviceType());
            query = MybatisPlusUtil.customEqQuery(query, "device_socket", param.getDeviceSocket());
            query = MybatisPlusUtil.customEqQuery(query, "platform_type", param.getPlatformType());
            query = MybatisPlusUtil.customLikeQuery(query, "imei", param.getImei());
        }

        IPage<DeviceBase> deviceBasePage = deviceBaseManager.page(new Page<DeviceBase>(currentPage, pageSize).setDesc("id"), query);

        List<JSONObject> records = deviceBasePage.getRecords().stream()
                .map(item -> {
                    JSONObject jsonObject = (JSONObject) JSON.toJSON(item);
                    Optional<DeviceType> deviceType = DeviceType.valueOf(item.getDeviceType());
                    Optional<DeviceSocket> deviceSocket = DeviceSocket.valueOf(item.getDeviceSocket());
                    Optional<PlatformType> platformType = PlatformType.valueOf(item.getPlatformType());

                    CompanyBase companyBase = companyBaseManager.getById(item.getCompanyId());

                    CompanyDeviceWeb companyDeviceWeb = null;
                    if (companyBase != null) {
                        companyDeviceWeb = companyDeviceWebManager.getCompanyDeviceWeb(companyBase.getId(), item.getId());
                    }

                    return jsonObject.fluentPut("deviceType_desc", deviceType.isPresent() ? deviceType.get().toString() : null)
                            .fluentPut("deviceSocket_desc", deviceSocket.isPresent() ? deviceSocket.get().toString() : null)
                            .fluentPut("platformType_desc", platformType.isPresent() ? platformType.get().toString() : null)
                            .fluentPut("company_name", companyBase == null ? "--" : companyBase.getCompanyName())
                            .fluentPut("webType", companyDeviceWeb == null ? null : companyDeviceWeb.getWebType())
                            .fluentPut("webTypeDesc", companyDeviceWeb == null ? "--" : ToWebType.valueOf(companyDeviceWeb.getWebType()).get().getDesc());
                }).collect(Collectors.toList());
        return new JSONObject().fluentPut("total", deviceBasePage.getTotal()).fluentPut("records", records);
    }

    public void bind(Long companyId, Long deviceId, Integer toweb, Date now) {
        try {
            companyDeviceWebManager.save(CompanyDeviceWeb.builder()
                    .companyBaseId(companyId)
                    .deviceBaseId(deviceId)
                    .webType(toweb)
                    .ctime(now)
                    .build());
        } catch (DuplicateKeyException e) {
            throw new VerifyException("该设备已为该公司分配展示位置");
        }

    }

    public void unbind(Long companyId, Long deviceId) {
        companyDeviceWebManager.remove(companyId, deviceId);
    }
}
